package end;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.swing.tree.DefaultMutableTreeNode;

public class Tree2RSF {

	private DefaultMutableTreeNode tree;
	
	/**
	 * Construct a transfomer which transforms the source tree to
	 * the target rsf file. 
	 * 
	 * @param a_tree	The source tree.
	 */
	public Tree2RSF(DefaultMutableTreeNode a_tree) {
		tree = a_tree;
	}
	
	/**
	 * Transform the source tree to the target rsf file.
	 * Write the decomposition represented by the tree into the 
	 * target rsf file; the file name is stored in the root of 
	 * the source tree. 
	 * 
	 * @return	The file name of the target rsf file.
	 * @throws IOException 
	 */
	public String tree2rsf() throws IOException {	
		// Obtain the target file name from the root.
		String result = (String)tree.getUserObject();
		PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(result)));
		
		DefaultMutableTreeNode node = null;
		DefaultMutableTreeNode parent_node = null;
		DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree.getRoot();
		Enumeration allNodes = root.breadthFirstEnumeration();
		
		// Get rid of the root node which contains only  
		// the target rsf file name.
		node = (DefaultMutableTreeNode) allNodes.nextElement();
		
		/*
		 * For each node in the tree print its parent
		 * following the rsf format if its parent is
		 * not the root. 
		 */
		while (allNodes.hasMoreElements()) {
			node = (DefaultMutableTreeNode) allNodes.nextElement();
			parent_node = (DefaultMutableTreeNode) node.getParent();
			if (parent_node != root) {
				out.println("contain "
						+ (String) parent_node.getUserObject() + " "
						+ (String) node.getUserObject());
			}
		}
		out.close();
		return result;
	}
}